package com.example.chirdrenserver.controller;


import com.example.chirdrenserver.Holder.UserHolder;
import com.example.chirdrenserver.Pojo.dto.FileDTO;
import com.example.chirdrenserver.Pojo.entity.File;
import com.example.chirdrenserver.Service.FileService;
import com.example.chirdrenserver.Utils.Result;
import com.example.chirdrenserver.confg.LocalCache;
import com.example.chirdrenserver.confg.QiNiuConfig;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @Author: Yu
 * @CreateTime: 2025-07-02
 * @Description:
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;
    @Autowired
    private QiNiuConfig qiNiuConfig;


    /**
     * 将数云端据保存到数据库
     *
     * @return
     */
    @PostMapping
    public Result save(@RequestBody FileDTO fileDTO) {

        return Result.success(fileService.save(fileDTO));
    }

    /**
     * 获得文件上传的token
     *
     * @param type
     * @return
     */
    @GetMapping("/getToken")
    public Result token(String type) {

        return Result.success(qiNiuConfig.uploadToken(type));
    }

    /**
     * 下传文件
     *
     * @param response
     * @param fileId
     * @throws IOException
     */
    @GetMapping("/{fileId}")
    public Result getUUid(HttpServletResponse response, @PathVariable Long fileId) throws IOException {

     /*   String ip = request.getHeader("referer");
        if (!LocalCache.containsKey(ip)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }*/
        // 如果不是指定ip调用的该接口，则不返回
        File url = fileService.getFileTrustUrl(fileId);

       return Result.success(url.getFileKey());
    }



    /**
     * 回调
     *
     * @param uuid
     * @param response
     * @throws IOException
     */
    @PostMapping("/auth")
    public void auth(@RequestParam(required = false) String uuid, HttpServletResponse response) throws IOException {
        if (uuid == null || LocalCache.containsKey(uuid) == null) {
            response.sendError(401);
        } else {
            LocalCache.rem(uuid);
            response.sendError(200);
        }
    }
}
